package com.ruoyi.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.TaskConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.TeamEnums;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.common.utils.uuid.UniqueInvitationCodeGenerator;
import com.ruoyi.system.coretools.LanguageUtil;
import com.ruoyi.system.coretools.mail.MailUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.handler.TaskHandler;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.rmi.ServerException;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.ruoyi.common.constant.TaskConstants.*;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    // 引入线程池
    private ThreadPoolTaskExecutor executor = SpringUtils.getBean("threadPoolTaskExecutor");
    @Value("${spring.mail.username}")
    String from;

    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private ITBaseInfoService baseInfoService;
    @Resource
    private ITTaskInfoService taskInfoService;
    @Resource
    private ITTaskPicService taskPicService;
    @Resource
    private ITTaskBaseService taskBaseService;
    @Resource
    private ITUserInfoService userInfoService;
    @Resource
    private TaskHandler taskHandler;
    @Resource
    private TVipMapper vipMapper;
    @Resource
    private TUserVipMapper userVipMapper;
    @Resource
    private TUserTaskInfoMapper userTaskInfoMapper;
    @Resource
    private TUserMoneyChangeMapper moneyChangeMapper;
    @Resource
    private SysDictDataMapper dictDataMapper;
    @Resource
    private TUserSignMapper signMapper;
    @Resource
    private TUserInfoMapper userInfoMapper;
    @Autowired
    private RedisCache redisCache;
    @Resource
    private LanguageUtil languageUtil;


    @Override
    public AjaxResult getLangList() {
        List<SysDictData> redisCacheCacheObject = redisCache.getCacheList("langCode");
        if (redisCacheCacheObject!=null&&!redisCacheCacheObject.isEmpty()) {
            return AjaxResult.success(redisCacheCacheObject);
        } else {
            List<SysDictData> lang_list = dictDataMapper.selectDictDataByType("lang_list");
            redisCache.setCacheList("langCode", lang_list);
            return AjaxResult.success(lang_list);
        }
    }

    @Override
    public AjaxResult selectBaseInfo(TBaseInfoDto baseInfo) {
        PageHelper.startPage(baseInfo);
        List<TBaseInfo> list = baseInfoService.selectListByCondition(baseInfo);
        PageInfo<TBaseInfo> page = new PageInfo<>(list);
        languageUtil.LanguageResult(list);
        return AjaxResult.success(page);
    }


    @Override
    public AjaxResult selectTaskInfo(TTaskInfoDto taskInfo) {
        PageHelper.startPage(taskInfo);
        List<TTaskInfoDto> list = taskInfoService.selectTaskInfo(taskInfo);
        PageInfo<TTaskInfoDto> page = new PageInfo<>(list);
        List<TTaskInfoDto> infoList = page.getList();
        if (!CollectionUtils.isEmpty(infoList)) {
            List<Long> taskIds = infoList.stream().map(TTaskInfoDto::getId).collect(Collectors.toList());
            // 查询步骤图
            List<TTaskPicDto> picList = taskPicService.selectPicByTaskIds(taskIds,1);
            // 查询标签信息
            List<TBaseInfoDto> baseList = baseInfoService.selectPicByTaskIds(taskIds,1);
            Map<String, List<TBaseInfoDto>> baseMap = baseList.stream().collect(Collectors.groupingBy(v -> v.getTaskId().toString()));
            Map<String, List<TTaskPicDto>> picMap = picList.stream().collect(Collectors.groupingBy(v -> v.getTaskId().toString()));
            infoList.forEach(vo -> {
                List<TTaskPicDto> tTaskPicDtos = picMap.get(vo.getId().toString());
                if (!CollectionUtils.isEmpty(tTaskPicDtos)) {
                    vo.setTaskPicList(tTaskPicDtos);
                }
                List<TBaseInfoDto> tBaseInfoDtos = baseMap.get(vo.getId().toString());
                if (!CollectionUtils.isEmpty(tBaseInfoDtos)) {
                    vo.setBaseDtoList(tBaseInfoDtos);
                }
            });
        }
        languageUtil.LanguageResult(list);
        return AjaxResult.success(page);
    }


    @Override
    public AjaxResult getTaskBaseByCondition(TBaseInfoDto baseInfoDto) {
        List<TBaseInfoDto> result = baseInfoService.getTaskBaseByCondition(baseInfoDto);
        languageUtil.LanguageResult(result);
        return AjaxResult.success(result);
    }

    /**
     * 获取首页任务列表-通过不同的数据来搜索
     *
     * @return
     */
    @Override
    public AjaxResult getHomeTaskByType(ConditionReq req) {
        Long lobbyTaskTypeId = req.getLobbyTaskTypeId();
        if (lobbyTaskTypeId != null) {
            TTaskBase tTaskBase = new TTaskBase();
            tTaskBase.setBaseId(lobbyTaskTypeId);
            List<TTaskBase> tTaskBases = taskBaseService.selectTTaskBaseList(tTaskBase);
            if (CollectionUtils.isEmpty(tTaskBases)) {
                PageHelper.startPage(req);
                List<TTaskInfoDto> homeTaskByType = new ArrayList<>();
                PageInfo<TTaskInfoDto> tTaskInfoDtoPageInfo = new PageInfo<>(homeTaskByType);
                return AjaxResult.success(tTaskInfoDtoPageInfo);
            }
            List<Long> taskIds = tTaskBases.stream().map(TTaskBase::getTaskId).collect(Collectors.toList());
            req.setTaskIds(taskIds);
        }
        PageHelper.startPage(req);
        List<TTaskInfoDto> homeTaskByType = taskInfoService.getHomeTaskByType(req);
        PageInfo<TTaskInfoDto> tTaskInfoDtoPageInfo = new PageInfo<>(homeTaskByType);
        languageUtil.LanguageResult(homeTaskByType);
        return AjaxResult.success(tTaskInfoDtoPageInfo);
    }

    @Override
    public AjaxResult taskInfo(ConditionReq req) {
        Long taskId = req.getTaskId();
        if (Objects.isNull(taskId)) {
            throw new ServiceException("任务id不能为空");
        }
        TTaskInfo taskInfo = taskInfoService.selectTTaskInfoById(taskId);
        if (Objects.isNull(taskInfo)) {
            throw new ServiceException("任务不存在");
        }
        TTaskInfoDto tTaskInfoDto = new TTaskInfoDto();
        BeanUtils.copyBeanProp(tTaskInfoDto, taskInfo);
        // 默认任务为待提交
        tTaskInfoDto.setAuditStatus(1);
        // 获取任务标签
        List<Long> taskIds = Arrays.asList(taskId);
        List<TBaseInfoDto> demand = baseInfoService.selectPicByTaskIds(taskIds,4);
        tTaskInfoDto.setDemandList(demand);
        //查看流程图
        List<TTaskPicDto> tTaskPicDtos = taskPicService.selectPicByTaskIds(taskIds,1);
        tTaskInfoDto.setTaskPicList(tTaskPicDtos);
        Long userId = req.getUserId();
        if (userId == null){
            req.setUserId(SecurityUtils.getApiUser().getUserId());
        }
        // 是否已截取任务
        List<TUserTaskInfo> tUserTaskInfos = userTaskInfoMapper.selectUserTask(taskId, req.getUserId());
        if (!CollectionUtils.isEmpty(tUserTaskInfos)) {
            tTaskInfoDto.setAccessStatus(1);
            for (int i = 0; i < tUserTaskInfos.size(); i++) {
                if (i == 0) {
                    TUserTaskInfo tUserTaskInfo = tUserTaskInfos.get(0);
                    String reason = tUserTaskInfo.getReason();
                    tTaskInfoDto.setReason(reason);
                    tTaskInfoDto.setAuditStatus(tUserTaskInfo.getAuditStatus());
                    // 查看回显信息 接取任务时的数据
                    tTaskInfoDto.setPicVoucher(tUserTaskInfo.getPicVoucher());
                    tTaskInfoDto.setContentText(tUserTaskInfo.getContentText());
                    // 回显提交任务的数据
                    Long userTaskInfoId = tUserTaskInfo.getId();
                    List<TTaskPicDto> subPicList = taskPicService.selectPicByTaskIds(Arrays.asList(userTaskInfoId),2);
                    Map<Integer, List<TTaskPicDto>> taskPicMap = subPicList.stream().collect(Collectors.groupingBy(TTaskPicDto::getInfoType));
                    tTaskInfoDto.setSubmitTaskPicList(taskPicMap.get(1));
                    tTaskInfoDto.setSubmitTaskContentList(taskPicMap.get(2));
                } else {
                    Long id = tUserTaskInfos.get(i).getId();
                    userTaskInfoMapper.deleteTUserTaskInfoById(id);
                }
            }
        }else {
            tTaskInfoDto.setAccessStatus(2);
        }
        languageUtil.LanguageResult(tTaskInfoDto);
        languageUtil.LanguageResult(tTaskInfoDto);
        return AjaxResult.success(tTaskInfoDto);
    }

    @Override
    public AjaxResult exchangeTask(ConditionReq req) {
        List<Long> longs = taskInfoService.selectTaskNotId(req.getTaskId());
        if (CollectionUtils.isEmpty(longs)){
            throw new ServiceException("当前没有可更换的任务");
        }
        Random random = new Random();
        int randomNumber = random.nextInt(longs.size());
        Long aLong = longs.get(randomNumber);
        req.setTaskId(aLong);
        return taskInfo(req);
    }

    @Override
    public AjaxResult accessTask(ConditionReq req) {
        Long loginUser = SecurityUtils.getApiUser().getUserId();
        Long taskId = req.getTaskId();
        // 查看用户是否已接当前任务，且没有完成
        List<TUserTaskInfo> tUserTaskInfos = userTaskInfoMapper.selectUserAbjectTask(taskId, loginUser);
        if (!CollectionUtils.isEmpty(tUserTaskInfos)) {
            throw new ServiceException("当前任务已接取过，不可重复截取！");
        }
        // 任务的可接数量是否可接
        TTaskInfo taskInfo = taskInfoService.checkTaskStatus(taskId);
        //校验接取任务需要的认证 需要采集截取任务用户信息（0-所有；1-文本信息；2-图
//        Integer needInfo = taskInfo.getNeedInfo();
//        if (TaskConstants.taskNeedPic.equals(needInfo) && StringUtils.isEmpty(req.getPicVoucher())) {
//            throw new ServiceException("需要上传接取任务凭证");
//        }
//        if (TaskConstants.taskNeedText.equals(needInfo) && StringUtils.isEmpty(req.getContentText())) {
//            throw new ServiceException("需要填写接取任务信息");
//        }
//        if (TaskConstants.taskNeedAll.equals(needInfo) && (StringUtils.isEmpty(req.getContentText()) || StringUtils.isEmpty(req.getPicVoucher()))) {
//            throw new ServiceException("请填入任务需求信息");
//        }
        // 确认用户是否达到接取任务上线
        TUserInfo userInfo = userInfoService.getById(loginUser);
        Date nowTime = new Date();
        String ymd = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, nowTime);
        // 通过vip等级获取vip信息
        TUserVip tVip = checkUserVip(userInfo.getId());
        Integer taskNum = tVip.getTaskNum();// 可接任务数量

        if (ymd.equals(userInfo.getAccessTime()) && taskNum > userInfo.getAccessNum()) {
            // 校验
            Long accessNum = userInfo.getAccessNum();
            userInfo.setAccessNum(accessNum + 1);
        } else if (!ymd.equals(userInfo.getAccessTime()) && taskNum > 0) {
            userInfo.setAccessNum(1l);
            userInfo.setAccessTime(ymd);
        } else {
            throw new ServiceException("接取任务已打上线，请升级会员");
        }
        // 修改任务接取数量
        taskInfoService.addTaskAbjectNum(taskInfo);
        userInfoMapper.updateById(userInfo);
        // 创建用户任务
        TUserTaskInfo tUserTaskInfo = new TUserTaskInfo();
        tUserTaskInfo.setTaskId(taskId);
        tUserTaskInfo.setPicVoucher(req.getPicVoucher());
        tUserTaskInfo.setContentText(req.getContentText());
        tUserTaskInfo.setUserId(loginUser);
        tUserTaskInfo.setStatus(0);
        tUserTaskInfo.setAuditStatus(1);
        tUserTaskInfo.setCreateTime(nowTime);
        tUserTaskInfo.setMoney(taskInfo.getTaskMoney());
        // 设置任务结束时间
        Date taskFinishTime = taskInfo.getTaskFinishTime();
        Integer finishTime = taskInfo.getFinishTime();
        Date taskEndTime = DateUtils.addDays(nowTime, finishTime);
        tUserTaskInfo.setFinishTime(taskEndTime);
        if (taskEndTime.after(taskFinishTime)){
            tUserTaskInfo.setFinishTime(taskFinishTime);
        }
        tUserTaskInfo.setCreateBy(loginUser.toString());
        tUserTaskInfo.setUpdateTime(nowTime);
        userTaskInfoMapper.insert(tUserTaskInfo);
        // 确认用户是否已接取任务
        return AjaxResult.success();
    }

    @Override
    public AjaxResult userTaskList(ConditionReq req) {
        Long userId = SecurityUtils.getApiUser().getUserId();
        req.setUserId(userId);
        // 查询自己接取的任务列表
        PageHelper.startPage(req);
        List<UserTaskStatusDto> list = userTaskInfoMapper.userTaskList(req);
        PageInfo<UserTaskStatusDto> pageInfo = new PageInfo<>(list);
        return AjaxResult.success(pageInfo);
    }

    /**
     * 个人中心信息
     *
     * @return
     */
    @Override
    public AjaxResult getUserInfo() {
        // 获取个人信息；订单量，和佣金统计信息
        Long userId = SecurityUtils.getApiUser().getUserId();
        TUserInfoDto userInfo = userInfoService.getUserById(userId);
        // 获取今日收益，统计收益，账户余额
        String ymd = DateUtils.getDate();
        List<TUserMoneyChange> moneyList = moneyChangeMapper.selectByUserId(userId, ymd);
        BigDecimal todayMoney = moneyList.stream().map(TUserMoneyChange::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        userInfo.setTodayEarnings(todayMoney);
        // 总收益在用户信息中有统计
//        BigDecimal bigDecimal = moneyChangeMapper.selectByUserIdTotal(userId);
//        userInfo.setEarnings(bigDecimal);
        TUserVip tUserVip = checkUserVip(userId);
        List<TaskNumDto> taskNum = userTaskInfoMapper.getUserTaskListStatistics(userId);
        Map<String, Integer> taskNumMap = taskNum.stream().collect(Collectors.toMap(TaskNumDto::getAuditStatus, TaskNumDto::getNum));
        Integer fail = taskNumMap.get(TaskConstants.taskAudit_fail);
        Integer success = taskNumMap.get(TaskConstants.taskAudit_success);
        Integer submitted = taskNumMap.get(TaskConstants.taskAudit_submitted);
        Integer reviewed = taskNumMap.get(TaskConstants.taskAudit_reviewed);
        userInfo.setVipLevel(tUserVip.getLevel());
        userInfo.setVipEndTime(tUserVip.getEndTime());

        userInfo.setSuccessNum(success == null ? 0 : success);
        userInfo.setSubmittedNum(submitted == null ? 0 : submitted);
        userInfo.setReviewedNum(reviewed == null ? 0 : reviewed);
        userInfo.setFailNum(fail == null ? 0 : fail);
        // todo 待完成邀请和展示邀请码
        userInfo.setUserCode("");
        languageUtil.LanguageResult(userInfo);
        return AjaxResult.success(userInfo);
    }

    @Override
    public AjaxResult getUserMoney() {
        // 获取个人信息；订单量，和佣金统计信息
        Long userId = SecurityUtils.getApiUser().getUserId();
        TUserInfoDto userInfo = userInfoService.getUserById(userId);
        // 获取今日收益，统计收益，账户余额
        String ymd = DateUtils.getDate();
        List<TUserMoneyChange> moneyList = moneyChangeMapper.selectByUserId(userId, ymd);
        BigDecimal todayMoney = moneyList.stream().map(TUserMoneyChange::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        userInfo.setTodayEarnings(todayMoney);
        languageUtil.LanguageResult(userInfo);
        return AjaxResult.success(userInfo);
    }

    @Override
    public AjaxResult getUserTaskListStatistics() {
        // 获取个人任务完成状态的总数量
//        Long userId = SecurityUtils.getUserId();
//        List<TUser> userTaskInfoMapper.getUserTaskListStatistics(userId);
        return null;
    }

    /**
     * 提交任务
     * 确认提交的资料是我们需要的资料
     * 然后数据落库等待审核
     *
     * @param req
     * @return
     */
    @Override
    public AjaxResult submitTask(TTaskInfoDto req) {
        Long userId = SecurityUtils.getApiUser().getUserId();
        if (Objects.isNull(req.getId())) {
            throw new ServiceException("任务id不能为空");
        }
        // 获取任务信息
        TTaskInfo taskInfo = taskInfoService.getById(req.getId());
        if (Objects.isNull(taskInfo)) {
            throw new ServiceException("任务不存在");
        }
        // 检测任务状态
        taskHandler.checkSubmitTask(taskInfo);
        // 任务状态正常，检查需要的资料
        List<TTaskPicDto> tTaskPicDtos = this.checkSubmitTaskInfo(req, taskInfo);
        // 一次能提交一个任务
        List<TUserTaskInfo> tUserTaskInfos = userTaskInfoMapper.selectUserTask(req.getId(), userId);
        if (CollectionUtils.isEmpty(tUserTaskInfos)) {
            throw new ServiceException("提交任务不存在");
        }
        TUserTaskInfo tUserTaskInfo = null;
        for (int i = 0; i < tUserTaskInfos.size(); i++) {
            if (i == 0) {
                tUserTaskInfo = tUserTaskInfos.get(0);
            } else {
                Long id = tUserTaskInfos.get(i).getId();
                userTaskInfoMapper.deleteTUserTaskInfoById(id);
            }
        }
        Date finishTime = tUserTaskInfo.getFinishTime();
        Date nowTime = new Date();
        if (finishTime.compareTo(nowTime) < 0) {
            tUserTaskInfo.setStatus(2);
            userTaskInfoMapper.updateById(tUserTaskInfo);
            // todo 任务接取去量减一
            taskInfoService.delTaskAbjectNum(taskInfo);
            return AjaxResult.error("任务已过期，请重新接取任务！");
        }
        // 处理任务对象
        taskPicService.synTaskPic(tTaskPicDtos,tUserTaskInfo);
        //0-已驳回；1-待提交；2-提交待审核；3-通过
        tUserTaskInfo.setAuditStatus(2);
        userTaskInfoMapper.updateById(tUserTaskInfo);
        return AjaxResult.success();
    }


    /**
     * 用户注册
     *
     * @param userRegisterInfoDto
     * @return
     */
    @Override
    public TUserInfo userRegister(TUserRegisterInfoDto userRegisterInfoDto) {
        log.info("收到用户注册请求:{}", userRegisterInfoDto);

        if (StringUtils.isEmpty(userRegisterInfoDto.getRegisterType())) {
            throw new ServiceException("注册类型不能为空,且只能是email和phone当中的一个");
        }

        //检查入参
        if (StringUtils.isEmpty(userRegisterInfoDto.getRegisterType())) {
            throw new ServiceException("注册类型不能为空,且只能是email和phone当中的一个");
        }
        if (StringUtils.isEmpty(userRegisterInfoDto.getRegisterWord())) {
            throw new ServiceException("密码不能为空");
        }
        if (StringUtils.isEmpty(userRegisterInfoDto.getRegisterConfirmWord())) {
            throw new ServiceException("确认密码不能为空");
        }
        if (!userRegisterInfoDto.getRegisterWord().equals(userRegisterInfoDto.getRegisterWord())) {
            throw new ServiceException("密码和确认密码不一致请确认确认密码");
        }

        TUserInfo info = new TUserInfo();
        //判断注册类型
        if ("phone".equals(userRegisterInfoDto.getRegisterType())) {
            if (StringUtils.isEmpty(userRegisterInfoDto.getPhone())) {
                throw new ServiceException("手机注册phone参数不能为空");
            }


            //数据重复检查
            TUserInfo checkInfo = userInfoService.selectByPhone(userRegisterInfoDto.getEmail());
            if (checkInfo != null) {
                throw new ServiceException("此手机已经在系统存在，请更换后重新注册或直接登录。");
            }


            info.setPhone(userRegisterInfoDto.getPhone());
            info.setPhoneWord(userRegisterInfoDto.getRegisterWord());
            info.setMoney(new BigDecimal(0));
            info.setFreezMoney(new BigDecimal(0));


        } else if ("email".equals(userRegisterInfoDto.getRegisterType())) {
            if (StringUtils.isEmpty(userRegisterInfoDto.getEmail())) {
                throw new ServiceException("邮箱注册email参数不能为空");
            }
            if (!isEmail(userRegisterInfoDto.getEmail())) {
                throw new ServiceException("这不是一个有效的邮件地址");
            }


            //数据重复检查
            TUserInfo checkInfo = userInfoService.selectByEmail(userRegisterInfoDto.getEmail());
            if (checkInfo != null) {
                throw new ServiceException("此邮箱已经在系统存在，请更换后重新注册或直接登录。");
            }


            info.setUserEmail(userRegisterInfoDto.getEmail());
            info.setEmailWord(userRegisterInfoDto.getRegisterWord());
            info.setMoney(new BigDecimal(0));
            info.setFreezMoney(new BigDecimal(0));


            //邮箱要多个检查邮箱验证码
            /*String redisMailCode = redisCache.getCacheMapValue("mailcodes", userRegisterInfoDto.getEmail());
            if (!redisMailCode.equals(userRegisterInfoDto.getMailyzm())) {
                throw new ServiceException("检查邮箱验证码不通过");
            }*/


        } else {
            throw new ServiceException("注册类型只能是email和phone当中的一个");
        }
        //插入数据
        info.setUserStatus(0);
        info.setFisAsk(0);
        info.setFistDraw(0);
        info.setFistTask(0);
        info.setBailMoney(0l);
        info.setUpdateTime(new Date());
        info.setVersion(0l);
        //生成用户唯一邀请码
        String str = UUID.fastUUID().toString();
        String userCode = str.substring(str.length() - 6);
        info.setUserCode(userCode);
        if (userRegisterInfoDto.getYaoqingma() != null) {
            TUserInfo parentUser = userInfoService.selectByCode(userRegisterInfoDto.getYaoqingma());
            if (parentUser != null) {
                info.setParentId(parentUser.getId());
            } else {
                throw new ServiceException("用户注册时候填写了邀请码,但此邀请码在平台查不到邀请用户,请检查后正确填写邀请码。");
            }
        } else {
            info.setParentId(-1l);
        }

        userInfoService.insertTUserInfo(info);
        TUserVip tUserVip = this.makeVipV0(info.getId());
        info.setVipId(tUserVip.getId());
        // 如果有邀请人，确认邀请人并绑定邀请关系
        String yaoqingma = userRegisterInfoDto.getYaoqingma();
        if (StringUtils.isNotEmpty(yaoqingma)) {
            TUserInfo parentInfo = userInfoService.selectByCode(yaoqingma);
            if (Objects.nonNull(parentInfo)) {
                info.setParentId(parentInfo.getId());
                userInfoService.updateById(info);
                // 绑定邀请团队关系：向上找3级
                this.makeParentIds(parentInfo, info);
            }
        } else {
            info.setParentId(-1l);
        }
        //业务完成后删除验证码
        redisCache.deleteCacheMapValue("mailcodes", userRegisterInfoDto.getEmail());
        log.info("完成用户注册请求:{}", userRegisterInfoDto);
        //返回结果
        languageUtil.LanguageResult(info);
        return info;
    }

    private void makeParentIds(TUserInfo parentInfo, TUserInfo info) {
        ArrayList<TUserMoneyChange> tUserMoneyChanges = new ArrayList<>();
        TUserMoneyChange tUserMoneyChange = bangUserRelation(parentInfo.getId(), info.getId(), 1);
        tUserMoneyChanges.add(tUserMoneyChange);
        Long parentId = parentInfo.getParentId();
        if (Objects.nonNull(parentId)) {
            TUserInfo supperParent = userInfoService.getById(parentId);
            if (Objects.nonNull(supperParent)) {
                TUserMoneyChange tUserMoneyChangeTwo = bangUserRelation(supperParent.getId(), info.getId(), 2);
                tUserMoneyChanges.add(tUserMoneyChangeTwo);
                if (Objects.nonNull(supperParent.getParentId())) {
                    TUserMoneyChange tUserMoneyChangeThr = bangUserRelation(supperParent.getParentId(), info.getId(), 3);
                    tUserMoneyChanges.add(tUserMoneyChangeThr);
                }
            }
        }
        if (!CollectionUtils.isEmpty(tUserMoneyChanges)) {
            tUserMoneyChanges.forEach(changes -> {
                moneyChangeMapper.insert(changes);
            });
        }

    }

    public TUserMoneyChange bangUserRelation(Long parentId, Long userId, Integer level) {
        TUserMoneyChange tUserMoneyChange = new TUserMoneyChange();
        tUserMoneyChange.setType(6);
        tUserMoneyChange.setUserId(parentId);
        tUserMoneyChange.setSourceUserId(userId);
        tUserMoneyChange.setIsDelete(1);
        tUserMoneyChange.setAuditStatus(4);
        tUserMoneyChange.setTeamLevel(level);
        tUserMoneyChange.setCreateTime(new Date());
        return tUserMoneyChange;
    }


    /**
     * 邮箱注册发送验证码
     *
     * @param email
     * @return
     */
    @Override
    public AjaxResult sendMailCodeToMail(String email) {
        Random random = new Random();
        Integer code = random.nextInt(1000000);
        //格式化成6为字符串
        String mailCode = String.format("%06d", code);
        //把验证码放redis
        redisCache.setCacheMapValue("mailcodes", email, code);


        //发邮件
        try {

            //String to[] = new String[]{email};
            Thread thread = new Thread(() -> {
                MailUtil.sendSimpleMail("邮件验证验证码", mailCode, from, email);
            });
            thread.start();


        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("邮件发送出错,请正确配置邮件服务器信息");
        }

        return AjaxResult.success(code);
    }

    private Runnable createWrappedRunnable(final Runnable task) {
        return new Runnable() {
            public void run() {
                try {
                    task.run();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };
    }

    /**
     * 个人中心设置修改用户个人信息
     *
     * @param tUserInfo
     * @return
     */
    @Override
    public AjaxResult updateUserInfo(TUserInfo tUserInfo) {
        userInfoService.updateTUserInfo(tUserInfo);
        return AjaxResult.success();
    }


    @Override
    public TUserInfo userLogin(TUserInfoDto userInfoDto) {
        TUserInfo info = null;
        // 确定是否有邮箱登录
        String userEmail = userInfoDto.getUserEmail();
        String emailWord = userInfoDto.getEmailWord();

        if (StringUtils.isNotEmpty(userEmail)) {
            info = userInfoService.selectByEmail(userEmail);
            if (Objects.isNull(info)) {
                throw new ServiceException("账户密码错误");
            }
            if (!info.getEmailWord().equals(emailWord)) {
                throw new ServiceException("账户密码错误");
            }
        } else if (StringUtils.isNotEmpty(userInfoDto.getAppId())) {
            info = userInfoService.selectByIosId(userInfoDto.getAppId());
        } else if (StringUtils.isNotEmpty(userInfoDto.getPhone())) {
            info = userInfoService.selectByPhone(userInfoDto.getPhone());
            if (Objects.isNull(info)) {
                throw new ServiceException("账户密码错误");
            }
            if (!info.getPhoneWord().equals(userInfoDto.getPhoneWord())) {
                throw new ServiceException("账户密码错误");
            }
        } else {
            throw new ServiceException("登录类型错误");
        }
        return info;
    }


    //用户登录by google
    @Override
    public TUserInfo userLoginByGoogle(TUserInfoDto userInfoDto) {
        TUserInfo info = null;
        if (StringUtils.isNotEmpty(userInfoDto.getUserEmail())) {
            info = userInfoService.selectByEmail(userInfoDto.getUserEmail());
            if (Objects.isNull(info)) {
                throw new ServiceException("查询失败");
            }

        }
        return info;
    }

    //用户登录by apple(分离化，免得过多特殊化的东西不好改)
    @Override
    public TUserInfo userLoginByApple(TUserInfoDto userInfoDto) {
        TUserInfo info = null;
        if (StringUtils.isNotEmpty(userInfoDto.getUserEmail())) {
            info = userInfoService.selectByEmail(userInfoDto.getUserEmail());
            if (Objects.isNull(info)) {
                throw new ServiceException("查询失败");
            }

        }
        return info;
    }


    @Override
    public AjaxResult userTeam() {
        // 获取个人邀请码
        Long userId = SecurityUtils.getApiUser().getUserId();
        TUserInfo userInfo = userInfoService.getById(userId);
        UserTeamGrossDto res = new UserTeamGrossDto();
        String userCode = getUserCode(userInfo);
        res.setCode(userCode);
        ArrayList<UserTeamInfo> userTeamInfos = new ArrayList<>();
        for (TeamEnums team : TeamEnums.getTeamCode()) {
            UserTeamInfo userTeamInfo = new UserTeamInfo();
            userTeamInfo.setLevelCode(team.getCode());
            // 计算金额
            List<TUserMoneyChange> tUserMoneyChanges = moneyChangeMapper.selectByUserAndTeam(userId, team.getLevel());
            // 获取团队比例
            List<SysDictData> sysDictData = dictDataMapper.selectDictDataByType(team.getCode());
            SysDictData sysDictData1 = sysDictData.get(0);
            userTeamInfo.setRate(new BigDecimal(sysDictData1.getDictValue()));
            Set<Long> users = new HashSet<Long>();
            BigDecimal countMoney = tUserMoneyChanges.stream().map(v -> {
                users.add(v.getSourceUserId());
                return v.getMoney();
            }).reduce(BigDecimal.ZERO, BigDecimal::add);
            userTeamInfo.setMoney(countMoney);
            userTeamInfo.setUserCount(users.size());
            userTeamInfos.add(userTeamInfo);
        }
        res.setTeamInfoList(userTeamInfos);
        languageUtil.LanguageResult(res);
        return AjaxResult.success(res);
    }

    /**
     * 获取收益明细
     *
     * @param req
     * @return
     */
    @Override
    public AjaxResult getUserEarningsList(TTaskInfoDto req) {
        Long userId = SecurityUtils.getApiUser().getUserId();
        //收益类型 0-所有收益类型 1-任务收入；2-佣金收入
        Integer earningsType = req.getEarningsType();
        PageHelper.startPage(req);
        List<TUserMoneyChangeDto> userEarningsList = moneyChangeMapper.getUserEarningsList(userId, earningsType, req.getMoneyDetailType());
        PageInfo<TUserMoneyChangeDto> tUserMoneyChangeDtoPageInfo = new PageInfo<>(userEarningsList);
        languageUtil.LanguageResult(userEarningsList);
        return AjaxResult.success(tUserMoneyChangeDtoPageInfo);
    }

    @Override
    public AjaxResult memberList(TTaskInfoDto req) {
        Long userId = SecurityUtils.getApiUser().getUserId();
        Integer level = req.getLevel();
        // 先分页查询出下级用户
        PageHelper.startPage(req);
        List<UserDTO> userDTOS = userInfoService.selectNextUserList(userId, level);
        PageInfo<UserDTO> userDTOPageInfo = new PageInfo<>(userDTOS);
        List<UserDTO> userList = userDTOPageInfo.getList();
        List<Long> userIds = userList.stream().map(UserDTO::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(userIds)) {
            languageUtil.LanguageResult(userDTOS);
            return AjaxResult.success(userDTOPageInfo);
        }
        // 下级人数
        List<TUserInfo> tUserInfos = userInfoService.selectByParentIds(userIds);
        Map<String, List<TUserInfo>> patentIdMap = tUserInfos.stream().collect(Collectors.groupingBy(v -> Objects.isNull(v.getParentId()) ? "" : v.getParentId() + ""));
        List<TUserMoneyChange> tUserMoneyChanges = moneyChangeMapper.selectByUserAndTeamList(userId, level, userIds);
        Map<Long, List<TUserMoneyChange>> userMoneyMap = tUserMoneyChanges.stream().collect(Collectors.groupingBy(TUserMoneyChange::getSourceUserId));
        userList.forEach(userDTO -> {
            Long id = userDTO.getId();
            userDTO.setNextNum(0);
            List<TUserInfo> tUserInfos1 = patentIdMap.get(id + "");
            if (!CollectionUtils.isEmpty(tUserInfos1)) {
                userDTO.setNextNum(tUserInfos1.size());
            }
            List<TUserMoneyChange> tUserMoneyChanges1 = userMoneyMap.get(id);
            if (!CollectionUtils.isEmpty(tUserMoneyChanges1)) {
                BigDecimal money = tUserMoneyChanges1.stream().map(v -> v.getMoney() == null ? BigDecimal.ZERO : v.getMoney()).reduce(BigDecimal.ZERO, BigDecimal::add);
                userDTO.setMoney(money);
                userDTO.setTaskFinishNum(tUserMoneyChanges1.size());
            }
        });
        languageUtil.LanguageResult(userDTOPageInfo.getList());
        return AjaxResult.success(userDTOPageInfo);
    }

    @Override
    public AjaxResult vipList() {
        Long userId = SecurityUtils.getApiUser().getUserId();
        // 查看用户 vip信息
        List<VipDto> tVips = vipMapper.selectVipList();
        TUserVip tUserVip = checkUserVip(userId);
        tVips.forEach(v -> {
            if (v.getLevel().equals(tUserVip.getLevel())) {
                v.setUserStatus(1);
            } else {
                v.setUserStatus(0);
            }
        });
        languageUtil.LanguageResult(tVips);
        return AjaxResult.success(tVips);
    }

    @Override
    public AjaxResult vipBuy(Long id) {
        // 确认会员是否存在
        TVip tVip = vipMapper.selectById(id);
        if (tVip == null) {
            throw new ServiceException("会员信息不存在");
        }
        TUserInfo userInfo = userInfoService.getById(SecurityUtils.getApiUser().getUserId());
        TUserVip userVip = checkUserVip(userInfo.getId());
        if (userVip.getLevel() != 0) {
            throw new ServiceException("您已是Vip");
        }
        koukuan(userInfo, tVip.getMoney(), 4);
        // 给用户添加会员信息
        userInfo.setVipId(id);
        Date nowTime = new Date();
        // 添加一条vip信息
        TUserVip tUserVip = new TUserVip();
        tUserVip.setUserId(userInfo.getId());
        tUserVip.setCommissionScale(tVip.getCommissionScale());
        tUserVip.setContentInfo(tVip.getContentInfo());
        tUserVip.setCreateBy(userInfo.getId().toString());
        tUserVip.setCreateTime(nowTime);
        tUserVip.setRemark(tVip.getRemark());
        tUserVip.setWithdrawLimit(tVip.getWithdrawLimit());
        tUserVip.setWithdrawHandlingCharge(tVip.getWithdrawHandlingCharge());
        tUserVip.setTaskNum(tVip.getTaskNum());
        tUserVip.setName(tVip.getName());
        tUserVip.setMoney(tVip.getMoney());
        tUserVip.setLevel(tVip.getLevel());
        Integer keepDays = tVip.getKeepDays();
        if (keepDays > 0) {
            Date date = DateUtils.rollDay(nowTime, keepDays);
            Date endDate = DateUtils.getEndDate(date);
            tUserVip.setEndTime(endDate);
        }
        userVipMapper.insert(tUserVip);
        userInfo.setVipId(tUserVip.getId());
        userInfoService.updateById(userInfo);
        return AjaxResult.success(tUserVip.getLevel());
    }

    @Override
    public AjaxResult userSignList() {
        Long userId = SecurityUtils.getApiUser().getUserId();
        String ymd = DateUtils.getDate();
        String ym = ymd.substring(0, 7);
        // 通过年月查询用户的签到数据
        List<TUserSign> tUserSigns = signMapper.selectByMonth(ym, userId);
        languageUtil.LanguageResult(tUserSigns);
        return AjaxResult.success(tUserSigns);
    }

    @Override
    public AjaxResult userSign() {
        Long userId = SecurityUtils.getApiUser().getUserId();
        String ymd = DateUtils.getDate();
        List<TUserSign> tUserSigns = signMapper.selectUserSign(userId, ymd);
        if (CollectionUtils.isEmpty(tUserSigns)) {
            TUserSign newUser = new TUserSign();
            newUser.setUserId(userId);
            newUser.setSignMonth(ymd.substring(0, 7));
            newUser.setSignTime(ymd);
            signMapper.insert(newUser);
            // 获取签到奖励
            List<SysDictData> sysDictData = dictDataMapper.selectDictDataByType(SIGN_BASE_MONEY);
            List<SysDictData> dictDataList = sysDictData.stream().filter(v -> "base_money".equals(v.getDictLabel())||v.getDictValue().equals(sysDictData.size()+"")).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(dictDataList)){
                String s = dictDataList.stream().map(SysDictData::getDictLabel).collect(Collectors.toList()).toString();
                BigDecimal addMoney = dictDataList.stream().map(v -> {
                    String dictValue = v.getDictValue();
                    try {
                        return new BigDecimal(dictValue);
                    } catch (Exception e) {
                        return BigDecimal.ZERO;
                    }
                }).reduce(BigDecimal.ZERO, BigDecimal::add);
                // 给用户添加金额
                taskHandler.shouyi(userId,addMoney,7,s+"签到收入");
            }
            return AjaxResult.success();
        }
        throw new ServiceException("当日已完成签到");
    }

    @Override
    public AjaxResult turntableList() {
        List<SysDictData> sysDictData = dictDataMapper.selectDictDataByType(turntable);
        languageUtil.LanguageResult(sysDictData);
        return AjaxResult.success(sysDictData);
    }

    @Override
    public AjaxResult getTurntable(Long id) {
        Long userId = SecurityUtils.getApiUser().getUserId();
        TUserInfo userInfo = userInfoService.getById(userId);
        Integer turntableNum = userInfo.getTurntableNum();
        if (turntableNum>0){
            userInfo.setTurntableNum(turntableNum-1);
            userInfoService.updateById(userInfo);
        }else {
            throw new ServiceException("次数不足");
        }
        if (id != null) {
            SysDictData sysDictData = dictDataMapper.selectDictDataById(id);
            if (sysDictData!=null&&!"0".equals(sysDictData.getDictValue())) {
                String dictValue = sysDictData.getDictValue();
                BigDecimal bigDecimal = new BigDecimal(dictValue);
                taskHandler.shouyi(userId,bigDecimal,8,"抽奖获取"+sysDictData.getDictLabel());
            }
            return AjaxResult.success();
        }else {
            List<SysDictData> sysDictData = dictDataMapper.selectDictDataByType(turntable);
            Random random = new Random();
            int i = random.nextInt(100);
            int index = i % sysDictData.size();
            SysDictData sysDictData1 = sysDictData.get(index);
            BigDecimal bigDecimal = new BigDecimal(sysDictData1.getDictValue());
            taskHandler.shouyi(userId,bigDecimal,8,"抽奖获取"+sysDictData1.getDictLabel());
            languageUtil.LanguageResult(sysDictData1);
            return AjaxResult.success(sysDictData1);
        }
    }

    @Override
    public AjaxResult getTurntableLog(Integer pageSize,Integer pageNum) {
        Long userId = SecurityUtils.getApiUser().getUserId();
        PageHelper.startPage(pageNum,pageSize);
        List<TUserMoneyChange> tUserMoneyChanges = moneyChangeMapper.selectTurntableLog(userId);
        PageInfo<TUserMoneyChange> tUserMoneyChangePageInfo = new PageInfo<>(tUserMoneyChanges);
        languageUtil.LanguageResult(tUserMoneyChanges);
        return AjaxResult.success(tUserMoneyChangePageInfo);
    }

    /**
     * 获取抽奖次数和任务
     * @return
     */
    @Override
    public AjaxResult getTaskAndNum() {
        Long userId = SecurityUtils.getApiUser().getUserId();
        TUserInfo userInfo = userInfoService.getById(userId);
        // 用户抽奖次数
        Integer turntableNum = userInfo.getTurntableNum();
        //获取抽奖任务信息 ask_register ask_finish finish_task
        List<String> codeList = Arrays.asList("ask_register", "ask_finish", "finish_task");
        List<DrawList> drawLists = dictDataMapper.selectByCode(codeList);
        HashMap<String, Object> result = new HashMap<>();
        result.put("hasNum",turntableNum);
        result.put("act",drawLists);
        languageUtil.LanguageResult(result);
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult fistJob() {
        Long userId = SecurityUtils.getApiUser().getUserId();
        TUserInfo userInfo = userInfoService.getById(userId);
        //获取抽奖任务信息 ask_register ask_finish finish_task
        List<String> codeList = Arrays.asList("fist_task", "fist_draw", "fist_ask");
        List<DrawList> drawLists = dictDataMapper.selectByCode(codeList);
        drawLists.forEach(v->{
            String dictType = v.getDictType();
            if ("fist_task".equals(dictType)){
                v.setFinishStatus(userInfo.getFistTask());
            } if ("fist_draw".equals(dictType)){
                v.setFinishStatus(userInfo.getFistDraw());
            } if ("fist_ask".equals(dictType)){
                v.setFinishStatus(userInfo.getFisAsk());
            }
        });
        languageUtil.LanguageValue(drawLists);
        languageUtil.LanguageResult(drawLists);
        return AjaxResult.success(drawLists);
    }

    @Override
    public AjaxResult getTaskByType(ConditionReq req) {
        PageHelper.startPage(req);
        List<TTaskInfoDto> homeTaskByType = taskInfoService.getTaskByType(req);
        PageInfo<TTaskInfoDto> tTaskInfoDtoPageInfo = new PageInfo<>(homeTaskByType);
        // 把图文数据补上
        List<Long> ids = homeTaskByType.stream().map(TTaskInfoDto::getId).distinct().collect(Collectors.toList());
        List<TTaskPicDto> tTaskPicDtos = taskPicService.selectPicByTaskIds(ids, 1);
        // 查询标签信息
        List<TBaseInfoDto> tBaseInfoDtos = baseInfoService.selectPicByTaskIds(ids, 1);
        Map<String, List<TTaskPicDto>> collect = tTaskPicDtos.stream().collect(Collectors.groupingBy(v->v.getTaskId().toString()));
        Map<String, List<TBaseInfoDto>> baseMap = tBaseInfoDtos.stream().collect(Collectors.groupingBy(v->v.getTaskId().toString()));
        homeTaskByType.forEach(v->{
            List<TTaskPicDto> tTaskPicDtos1 = collect.get(v.getId().toString());
            List<TBaseInfoDto> baseInfoDtos = baseMap.get(v.getId().toString());
            v.setTaskPicList(tTaskPicDtos1);
            v.setBaseDtoList(baseInfoDtos);
        });
        languageUtil.LanguageResult(tTaskInfoDtoPageInfo.getList());
        return AjaxResult.success(tTaskInfoDtoPageInfo);
    }


    private String money_fix = "koukuan";

    /**
     * 扣款
     *
     * @param userInfo
     * @param money
     * @param type     3-体现支出；4-购买支出
     */
    public void koukuan(TUserInfo userInfo, BigDecimal money, Integer type) {
        //
        Object redisCacheCacheObject = redisCache.getCacheObject(money_fix + userInfo.getId());
        if (Objects.nonNull(redisCacheCacheObject)) {

        }
        BigDecimal haveMoney = userInfo.getMoney();
        if (haveMoney.compareTo(money) < 0) {
            throw new ServiceException("余额不足请充值");
        }
        // 余额重组，扣除费用
        BigDecimal residueMoney = haveMoney.subtract(money);
        userInfo.setMoney(residueMoney);
        Integer integer = userInfoService.updateMoney(residueMoney, userInfo.getVersion(), userInfo.getId());
        if (integer < 1) {
            koukuan(userInfo, money, type);
        }
        Date date = new Date();
        // 扣款成功继续向下操作 记录日志
        TUserMoneyChange tUserMoneyChange = new TUserMoneyChange();
        tUserMoneyChange.setType(type);
        tUserMoneyChange.setAuditStatus(2);
        tUserMoneyChange.setUserId(userInfo.getId());
        tUserMoneyChange.setBeforeMoney(haveMoney);
        tUserMoneyChange.setMoney(money);
        tUserMoneyChange.setTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date));
        tUserMoneyChange.setIsDelete(0);
        tUserMoneyChange.setCreateBy(userInfo.getId().toString());
        tUserMoneyChange.setCreateTime(date);
        tUserMoneyChange.setCreateTime(date);
        moneyChangeMapper.insert(tUserMoneyChange);
    }



    public TUserVip checkUserVip(Long userId) {
        TUserInfo user = userInfoService.getById(userId);
        // 查询用户的最新一条会员信息
        TUserVip tUserVip = userVipMapper.selectById(user.getVipId());
        if (Objects.isNull(tUserVip)) {
            // 查询vip为0 的那条数据
            return makeVipV0(user.getId());
        } else {
            // 不为空的情况检测
            Date endTime = tUserVip.getEndTime();
            Date date = new Date();
            if (tUserVip.getLevel() != 0 && date.compareTo(endTime) == 1) {
                // 会员失效
                return makeVipV0(user.getId());
            } else {
                return tUserVip;
            }
        }
    }

    public TUserVip makeVipV0(Long userId) {
        TVip tVip = vipMapper.selectByLevel(0);
        Date nowTime = new Date();
        TUserVip tUserVip = new TUserVip();
        tUserVip.setCommissionScale(tVip.getCommissionScale());
        tUserVip.setContentInfo(tVip.getContentInfo());
        tUserVip.setCreateBy(userId.toString());
        tUserVip.setCreateTime(nowTime);
        tUserVip.setRemark(tVip.getRemark());
        tUserVip.setWithdrawLimit(tVip.getWithdrawLimit());
        tUserVip.setWithdrawHandlingCharge(tVip.getWithdrawHandlingCharge());
        tUserVip.setTaskNum(tVip.getTaskNum());
        tUserVip.setName(tVip.getName());
        tUserVip.setMoney(tVip.getMoney());
        tUserVip.setUserId(userId);
        tUserVip.setLevel(tVip.getLevel());
        Integer keepDays = tVip.getKeepDays();
        if (keepDays > 0) {
            Date date = DateUtils.rollDay(nowTime, keepDays);
            Date endDate = DateUtils.getEndDate(date);
            tUserVip.setEndTime(endDate);
        }
        userVipMapper.insert(tUserVip);
        return tUserVip;
    }

    /**
     * 获取用户邀请唯一编码
     *
     * @param userInfo
     * @return
     */
    private String getUserCode(TUserInfo userInfo) {
        // 确认用户是否有邀请码，没有就生成一个
        String userCode = userInfo.getUserCode();
        if (StringUtils.isEmpty(userCode)) {
            String code = UniqueInvitationCodeGenerator.generateUniqueInvitationCode();
            // 确认没有用户存在
            TUserInfo hasUser = userInfoService.selectByCode(code);
            if (Objects.isNull(hasUser)) {
                userInfo.setUserCode(code);
                userInfoService.updateById(userInfo);
                return code;
            } else {
                return getUserCode(userInfo);
            }
        } else {
            return userCode;
        }
    }

    private List<TTaskPicDto> checkSubmitTaskInfo(TTaskInfoDto req, TTaskInfo taskInfo) {
        List<TTaskPicDto> picList = new ArrayList<>();
        //1-图片，2-文字
        List<TTaskPicDto> tTaskPicDtoText = req.getSubmitTaskContentList();
        if (!CollectionUtils.isEmpty(tTaskPicDtoText)) {
            fullTaskPic(tTaskPicDtoText, 2, 2);
            picList.addAll(tTaskPicDtoText);
        }
        List<TTaskPicDto> tTaskPicDtoPic = req.getSubmitTaskPicList();
        if (!CollectionUtils.isEmpty(tTaskPicDtoPic)) {
            fullTaskPic(tTaskPicDtoPic, 1, 2);
            picList.addAll(tTaskPicDtoPic);
        }
        return picList;
    }

    /**
     * @param list     数据集合
     * @param infoType 数据类型 1-图文；2-文本信息
     * @param type     数据类型1-任务流程图片；2-提交审核图片
     */
    private void fullTaskPic(List<TTaskPicDto> list, Integer infoType, Integer type) {
        Date nowTime = new Date();
        for (int i = 0; i < list.size(); i++) {
            TTaskPicDto tTaskPicDto = list.get(i);
            tTaskPicDto.setType(type);
            tTaskPicDto.setInfoType(infoType);
            tTaskPicDto.setIsDelete(0);
            tTaskPicDto.setSort(i);
            LoginUser apiUser = SecurityUtils.getApiUser();
            tTaskPicDto.setCreateBy(apiUser.getUsername());
            tTaskPicDto.setCreateTime(nowTime);
        }
    }

    private Boolean isEmail(String email) {
        String regEx1 = "^([a-z0-9A-Z]+[-|.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        return Pattern.compile(regEx1).matcher(email.trim()).matches();
    }

}
